package com.mt.mtyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.mtyx.acl.mapper.AdminMapper;
import com.mt.mtyx.acl.service.AdminService;
import com.mt.mtyx.common.utils.MD5;
import com.mt.mtyx.entity.acl.Admin;
import com.mt.mtyx.vo.acl.AdminQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户管理 业务层
 *
 * @author WMT
 * @Date 2023/6/25 20:47
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public IPage<Admin> getAdminList(Page<Admin> rolePage, AdminQueryVo adminQueryVo) {
        LambdaQueryWrapper<Admin> wrapper = null;
        if (adminQueryVo != null) {
            // 1.获取用户名称条件值
            String name = adminQueryVo.getName();
            // 2.创建条件构造器
            wrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(name)) {
                wrapper.like(Admin::getName, name);
            }
        }
        return baseMapper.selectPage(rolePage, wrapper);
    }

    @Override
    public Long countByUsername(String name) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,name);
        return baseMapper.selectCount(wrapper);
    }

    @Override
    public int insert(Admin admin) {
        LocalDateTime now = LocalDateTime.now();
        String password = MD5.encrypt(admin.getPassword());
        admin.setPassword(password);
        admin.setCreateTime(now);
        admin.setUpdateTime(now);
        return baseMapper.insert(admin);
    }

    @Override
    public int delete(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int batchRemove(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int update(Admin admin) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getId, admin.getId());
        admin.setUpdateTime(LocalDateTime.now());
        return baseMapper.update(admin,wrapper);
    }
}
